package com.tuoyu.peopletest.view.ac;

import static android.os.Build.MANUFACTURER;
import static android.os.Build.MODEL;
import static com.tuoyu.peopletest.common.MyApplication.context;
import static com.tuoyu.peopletest.utils.WebApi.*;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.stresscube.usbdevice.USBDevicePDHIDWithAddress;
import com.tuoyu.peopletest.R;
import com.tuoyu.peopletest.utils.WebApi;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MainActivityCortisolTest extends AppCompatActivity implements View.OnClickListener {
    static final String TAG = "MainStandardTest";
    static final byte testColor = 0x2A; //测试使用的颜色， 15为波长365，2A为波长470

    USBDevicePDHIDWithAddress mDeviceHID = new USBDevicePDHIDWithAddress();
    LineChart mLineChart;   //显示曲线
    TextView mtvMessage; //结果显示
    byte ledPosition = (byte) 0x03, color = (byte) 0x01; //孔位为3，颜色为孔1
    int mBrightness=800;
    byte adPosition = (byte) 0x01;
    ArrayList<Integer> mListResult = new ArrayList<>(); //保存读出来的数据

    int mStart=60, mStop=160, mStep=2; //起始位置、终止位置、每步几个点（最少1个点，此时采样频率为50Hz，为2时，采样频率为100Hz）
    private String mArea1, mArea2, mPeak1, mPeak2, mAverage;
    private String mCortisolResult;
    private String mStrNo; //测试序号

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_cortisol_test);

        InitData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mDeviceHID.init(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mDeviceHID.release();
    }

    void InitData() {
        mtvMessage = findViewById(R.id.tvMessage);
        mLineChart = findViewById(R.id.lineChart_01);

        mListResult.clear();
    }

    public void DisplayMessage(String msg) {
        Log.d(TAG, msg);
        msg += "\r\n" + mtvMessage.getText();
        mtvMessage.setText(msg);
    }

    public void DisplayAreaMessage(String msg) {
        ((TextView) findViewById(R.id.tvResultArea)).setText(msg);
        Log.d(TAG, msg);
    }

    public void DisplayAverageMessage(String msg) {
        ((TextView) findViewById(R.id.tvResultAverage)).setText(msg);
        Log.d(TAG, msg);
    }
    public void DisplayCortisolResultMessage(String msg) {
        ((TextView) findViewById(R.id.tvResult)).setText(msg);
        Log.d(TAG, msg);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnHome:
                Home();
                break;
            case R.id.btnTrayMoveStart:
                TrayMoveStart();
                break;
            case R.id.btnTrayMoveEnd:
                TrayMoveEnd();
                break;
            case R.id.btnScanRead:
                ScanRead();
                break;
            case R.id.btnMain:
                Intent mainIntent = new Intent(this, MainActivity.class);
                startActivity(mainIntent);
                finish();
                break;
            case R.id.btnMainTest:
                Intent mainTestIntent = new Intent(this, MainActivityTest.class);
                startActivity(mainTestIntent);
                finish();
                break;
            case R.id.btnWebApiGet:
                WebApiGet();
                break;
            case R.id.btnWebApiPost:
                WebApiPost();
                break;
        }
    }

    private void WebApiPost() {
        JSONObject obj = new JSONObject();
        try {
            obj.put("CreateTime","2023-06-06 15:06:30");
            obj.put("AppName","ScanPDTest");
            obj.put("Data","abcdef");
            obj.put("Bits",8);
            obj.put("Frequency",25);
            obj.put("Size",200);
            obj.put("StartPos",15);
            obj.put("EndPos",180);
            obj.put("Brightness",800);
            obj.put("LEDPosition",1);
            obj.put("ADPosition",1);
            obj.put("PeakValley",0);
            obj.put("WaveLength","470");
            obj.put("Comment","Test data send from android");
        } catch (Exception e) {
            e.printStackTrace();
        }
        WebApi webApi = new WebApi();
        HttpListener cb=new HttpListener(){
            public boolean onResponse(String response) {
                SendDispMessage("Post成功\r\n"+response);
                return true;
            }
            public void onSuccess(JSONObject response){
                SendDispMessage("Post成功\r\n"+response.toString());
            }
            public void onFailed(String message, int status){
                SendDispMessage("Post失败 code:"+status+"\r\n"+message);
            }
        };
        webApi.post("http://192.168.0.117:8080/ScanPD/", obj.toString(), cb);
    }
    private void WebApiGet() {
//        String textArray="[{\"id\":1,\"size\":5,\"comment\":\"first data\",\"data\":\"MTIzNDU2\",\"appName\":\"ScanPDTest\",\"brightness\":1,\"startPos\":15,\"peakValley\":0,\"waveLength\":470,\"endPos\":180,\"adposition\":1,\"bits\":2,\"frequency\":25,\"ledposition\":1,\"createTime\":\"2023-06-05T08:53:00.000+00:00\"}]";
//        String textObj="{\"array\":[{\"id\":1},{\"id\":2}]}";
//        for(int i=0;i<100;i++) {
//            try {
//                JSONObject jsonObject = new JSONObject(textObj);
//                JSONArray jsonArray = new JSONArray(textArray);
//                String text1 = jsonObject.toString();
//                String text2 = jsonArray.toString();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        WebApi webApi=new WebApi();
        HttpListener cb=new HttpListener(){
            public boolean onResponse(String response) {
                SendDispMessage("获取成功\r\n"+response);
                return true;
            }
            public void onSuccess(JSONObject response){
                SendDispMessage("获取成功\r\n"+response.toString());
            }
            public void onFailed(String message, int status){
                SendDispMessage("获取失败 code:"+status+"\r\n"+message);
            }
        };
        webApi.get("http://192.168.0.117:8080/ScanPD/", cb);
    }

    //计算峰值下的面积，一共2个峰，峰值左右各1mm，确定是向上的峰或向下的谷
    //左向外10个点及右向外10个点，取平均值，确定为基线
    int left = 10, right = 10, minGap = 50;//面积计算时，极值点左右的距离, minGap为两个峰值间的距离， 单位为0.1mm

    boolean getPeakPos(int[] data, List<Integer> listPeakPos, boolean bValley, int step) {
        int max1 = 0, max2 = 0, max2Left = 0, max2Right = 0;
        int iMax1 = 0, iMax2 = 0;
        if (bValley) {
            for (int iData = 0; iData < data.length; iData++) {
                data[iData] *= -1;
            }
            max2Left = max2Right = max1 = -256 * 256 * 256 * 127;
        }
        //找第1个峰
        for (int iData = 0; iData < data.length; iData++)
            if (data[iData] > max1) {
                max1 = data[iData];
                iMax1 = iData;
            }
        //找第2个峰
        int iMax2Left = 0, iMax2Right = 0;
        if (iMax1 > ((left + right) + left) * step) {
            for (int iData = left * step; iData < iMax1 - (left + right) * step; iData++)
                if (data[iData] > max2Left) {
                    max2Left = data[iData];
                    iMax2Left = iData;
                }
        }
        if ((data.length - iMax1) > ((left + right) + right) * step) {
            for (int iData = iMax1 + (left + right) * step; iData < data.length - right * step; iData++)
                if (data[iData] > max2Right) {
                    max2Right = data[iData];
                    iMax2Right = iData;
                }
        }
        if (max2Right > max2Left) {
            max2 = max2Right;
            iMax2 = iMax2Right;
        } else {
            max2 = max1;
            max1 = max2Left;
            iMax2 = iMax1;
            iMax1 = iMax2Left;
        }
        listPeakPos.clear();
        listPeakPos.add(iMax1);
        listPeakPos.add(iMax2);
        return true;
    }

    private String GetArea(int[] data, int step) {
        boolean bValley = false;
        List<Integer> listPeakPos = new ArrayList<>();
        getPeakPos(data, listPeakPos, bValley, step);
        if (listPeakPos.size() != 2)
            return "";
        int average = GetAverage(data, listPeakPos.get(0), listPeakPos.get(1), step);

        int[] areaLeft = new int[2];
        int[] areaRight = new int[2];
        int area1 = CalcArea(data, listPeakPos.get(0), step, average, areaLeft);
        int area2 = CalcArea(data, listPeakPos.get(1), step, average, areaRight);
        int max1 = data[listPeakPos.get(0)], max2 = data[listPeakPos.get(1)];
        SendDispAreaMessage("面积 " + area1 + " " + area2 + " 极值 " + max1 + " " + max2);

        mArea1 = area1 + "";
        mArea2 = area2 + "";
        mPeak1=max1+"";
        mPeak2=max2+"";
        mAverage=average+"";

        CalcResult(area1, area2);
        //保存数据
//        saveData();
        return areaLeft[0] + "\t" + areaRight[0] + "\t" + areaLeft[1] + "\t" + areaRight[1] + "\t" + max1 + "\t" + (max1 - average) + "\t" + average;
    }

    private void CalcResult(int area1, int area2) {
        double logS1S2=Math.log10(area1*1.0/area2);
        double logC=(logS1S2-0.86)/(-0.9297);
        double result=Math.pow(10, logC);
        result=((int)(result*100+0.5))/100.0;
        mCortisolResult=""+result;
        SendDispCortisolResultMessage("结果:"+result);
    }

    //给定点，算左右1mm的面积
    //首先计算左点外10个点和右点外10个点的平均值
    //再计算左右1mm内值减去平均值后的面积
    int nPointsForAverageLeft = 10, nPointsForAverageRight = 10;

    private int CalcArea(int[] data, int iMax, int step, int averageGlobal, int[] area2) {
        int nData = 0, sum = 0;
        for (int iData = iMax - left * step - nPointsForAverageLeft; iData < iMax - left * step; iData++) {
            if (iData <= 0)
                continue;
            sum += data[iData];
            nData++;
        }
        for (int iData = iMax + right * step; iData < iMax + right * step + nPointsForAverageRight * step; iData++) {
            if (iData >= data.length)
                break;
            sum += data[iData];
            nData++;
        }
        if (nData == 0)
            return -1;
        int average = sum / nData;
        int area = 0, areaSubGlobalAvg = 0;
        for (int iData = iMax - left * step; iData < iMax + right * step; iData++) {
            if (iData < 0 || iData >= data.length) {
                Log.d("area", "Data index error:" + iData);
                continue;
            }
            area += (data[iData] - average) / step;
            areaSubGlobalAvg += (data[iData] - averageGlobal) / step;
        }
        Log.d("", "area: " + area + " average: " + average);
        Log.d("", "areaSubGlobalAvg: " + areaSubGlobalAvg + " averageGlobal: " + averageGlobal);
        if (area2 != null) {
            area2[0] = area;
            area2[1] = areaSubGlobalAvg;
        }
        return area;
    }

    private boolean LEDOn() {
        return mDeviceHID.LEDOn(ledPosition, color, mBrightness);
    }

    private boolean LEDOff() {
        return mDeviceHID.LEDOn(ledPosition, (byte) 0x00, 0);
    }

    private void Home() {
        if (!mDeviceHID.GoHome())
            DisplayMessage("回原点失败");
        else
            DisplayMessage("回原点成功");
    }

    private void TrayMoveStart() {
        if (!mDeviceHID.MoveTray(mStart))
            DisplayMessage("托架移动起点失败");
        else
            DisplayMessage("托架移动起点成功");
    }

    private void TrayMoveEnd() {
        if (!mDeviceHID.MoveTray(mStop))
            DisplayMessage("托架移动终点失败");
        else
            DisplayMessage("托架移动终点成功");
    }

    private void ScanRead() {
        if(!getStep()) {
            SendDispMessage("读设备频率和增益出错, 停止检测");
            return;
        }
        if(!readFromDevice()) {
            SendDispMessage("读设备配置数据出错, 停止检测");
            return;
        }
        showConfigText();
        mStrNo=((EditText)findViewById(R.id.edtNo)).getText().toString();
        new Test().start();
    }

    private void showConfigText() {
        ((TextView)findViewById(R.id.tvStart)).setText(""+mStart);
        ((TextView)findViewById(R.id.tvStop)).setText(""+mStop);
        ((TextView)findViewById(R.id.tvStep)).setText(""+mStep);
        ((TextView)findViewById(R.id.tvBrightness)).setText(""+mBrightness);
    }

    private boolean readFromDevice() {
        byte[] data=new byte[7];
        if(!mDeviceHID.ReadMemoBlock(0, data)) {
            SendDispMessage( "读设备出错");
            return false;
        }
        int iData=0;
        if(data[iData]!=0x01||data[iData+1]!=0x01) {
            SendDispMessage( "数据版本不对");
            return false;
        }
        iData+=2;
        mStart=data[iData]&0xff;
        iData++;
        mStop=data[iData]&0xff;
        iData++;
        mBrightness=(data[iData]&0xff)*256+(data[iData+1]&0xff);
        iData+=2;
        color=data[iData];
        if(mStart<0||mStart>150) {
            SendDispMessage( "数据中开始位置不对");
            return false;
        }
        if(mStop<50||mStop>220) {
            SendDispMessage( "数据中结束位置不对");
            return false;
        }
        if(mBrightness<0||mBrightness>800) {
            SendDispMessage( "数据中亮度不对");
            return false;
        }
        return true;
    }

    boolean getStep() {
        int[] frequencyAndGain = new int[2];
        if (!mDeviceHID.GetADCFrequencyAndGain((byte) 0x01, frequencyAndGain))
            return false;
        if (frequencyAndGain[0] < 10 || frequencyAndGain[0] > 19200)
            return false;
        mStep = (int) (frequencyAndGain[0] / 50.0 + 0.5);
        if (mStep <= 0)
            mStep = 1;
        return true;
    }

    void SendDispMessage(String str) {
        Message message = new Message();
        message.what = 1;
        message.obj = str;
        mHandler.sendMessage(message);
    }

    void SendDispCortisolResultMessage(String str) {
        Message message = new Message();
        message.what = 7;
        message.obj = str;
        mHandler.sendMessage(message);
    }
    void SendDispAreaMessage(String str) {
        Message message = new Message();
        message.what = 5;
        message.obj = str;
        mHandler.sendMessage(message);
    }

    void SendDispAverageMessage(String str) {
        Message message = new Message();
        message.what = 6;
        message.obj = str;
        mHandler.sendMessage(message);
    }

    void SendDispData(int[] data) {
        Message message = new Message();
        message.what = 2;
        message.obj = data;
        mHandler.sendMessage(message);
    }

    void SendDispData(int data) {
        Message message = new Message();
        message.what = 4;
        message.obj = data;
        mHandler.sendMessage(message);
    }

    void DispCurve() {
        Message message = new Message();
        message.what = 3;
        mHandler.sendMessage(message);
    }

    public File getSaveFile() {
        File file = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            file = Environment.getExternalStorageDirectory();
        } else {
            file = getFilesDir();
        }

        if (file != null) {
            file = new File(file, "stresscube");
            if (!file.exists()) {
                file.mkdir();
            }
            file = new File(file, "scantestpd");
            if (!file.exists()) {
                file.mkdir();
            }
        }

        return file;
    }

    public String getDateString() {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date(System.currentTimeMillis()));
        String formatString = "yyyyMMddHHmmss";
        SimpleDateFormat sdf = new SimpleDateFormat(formatString, Locale.ENGLISH);
        return sdf.format(c.getTime());
    }
    public String getChineseDateString() {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date(System.currentTimeMillis()));
        String formatString = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(formatString, Locale.ENGLISH);
        return sdf.format(c.getTime());
    }

    private String getDataFilename() {
        return getSaveFile() + "/" + getDateString() + ".txt";
    }
    private String getCortisolFilename() {
        return getSaveFile() + "/" + "CortisolResult.txt";
    }

    class Test extends Thread {
        boolean bMove=true;
        public Test(boolean bMove) {
            this.bMove=bMove;
        }
        public Test(){}
        @Override
        public void run() { //改成发移动命令、连续获取AD、检测停止命令
            SendDispMessage("开始测试");

            if (!scanReadAD(true, mStart, mStop, mStep, mListResult,bMove))
                return;

            if (mListResult.size() > 10) {
                int[] data = new int[mListResult.size()];
                for (int i = 0; i < mListResult.size(); i++)
                    data[i] = mListResult.get(i);
                GetArea(data, mStep);
                if (SaveData(data)) {
//                    DisplayMessage("测试结束，保存数据成功");
                    DisplayMessage("测试号:"+mStrNo+"\t结果:"+mCortisolResult+" nmol/L\t保存数据成功");
                }
                else
                    DisplayMessage("测试号:"+mStrNo+"\t结果:"+mCortisolResult+" nmol/L\t保存失败!");
//                    DisplayMessage("测试结束，保存失败！");
            }
        }

        //把测试数据保存下来
        private boolean SaveData(int[] data) {
            try {
                String resultFileName = getDataFilename();
                FileOutputStream out = new FileOutputStream(resultFileName);
                out.write(("测试号: " + mStrNo + "\r\n").getBytes());
                out.write(("时间: " + getChineseDateString() + "\r\n").getBytes());
                out.write(("结果: " + mCortisolResult + "\r\n").getBytes());
                out.write(("" + mStart + " -> " + mStop + " step:"+ mStep+" 点/0.1mm\r\n").getBytes());
                out.write(("color:"+color+" 亮度:" + mBrightness + "\r\n").getBytes());
                out.write(("面积1: " + mArea1 + " 面积2:" + mArea2 + " 峰1："+mPeak1+" 峰2："+mPeak2+"平均值："+mAverage+"\r\n").getBytes());
                for (int i = 0; i < data.length; i++) {
                    out.write(("" + data[i] + "\r\n").getBytes());
                }
                out.flush();
                out.close();
                //最后保存下结果
                SaveCortisolResult();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        private boolean SaveCortisolResult() {
            try {
                String resultFileName = getCortisolFilename();
                boolean bNewFile = false;
                {
                    File result = new File(resultFileName);
                    if (!result.exists())
                        bNewFile = true;
                }
                FileOutputStream out = new FileOutputStream(resultFileName, true);
                if(bNewFile)
                    out.write(("测试号\t结果\t面积1\t面积2\t峰1\t峰2\t平均值\t时间\r\n").getBytes());
                out.write((mStrNo + "\t").getBytes());
                out.write((mCortisolResult + "\t").getBytes());
                out.write((mArea1 + "\t"+mArea2+"\t").getBytes());
                out.write((mPeak1 + "\t"+mPeak2+"\t").getBytes());
                out.write((mAverage + "\t").getBytes());
                out.write((getChineseDateString() + "\r\n").getBytes());
                out.flush();
                out.close();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    private int GetAverage(int[] data, int iMaxLeft, int iMaxRight, int step) {
        int[] newDatas = new int[data.length];
        for (int i = 0; i < data.length; i++)
            newDatas[i] = data[i];
        for (int i = 0; i < 5; i++)
            newDatas[i] = -1;
        for (int i = iMaxLeft - left * step; i < iMaxLeft + left * step; i++) {
            if (i <= 0)
                continue;
            if (i >= data.length)
                break;
            newDatas[i] = -1;
        }
        for (int i = iMaxRight - right * step; i < iMaxRight + right * step; i++) {
            if (i <= 0)
                continue;
            if (i >= data.length)
                break;
            newDatas[i] = -1;
        }
        int average = 0;
        while (true) {
            double sum = 0;
            int num = 0;
            int max = -1, imax = -1;
            int min = 0, imin = -1;
            for (int i = 0; i < newDatas.length; i++)
                if (newDatas[i] > 0) {
                    sum += newDatas[i];
                    num++;
                    if (imax < 0 || max < newDatas[i]) {
                        max = newDatas[i];
                        imax = i;
                    }
                    if (imin < 0 || min > newDatas[i]) {
                        min = newDatas[i];
                        imin = i;
                    }
                }
            average = (int) (sum / num + 0.5);
            if (num <= 10)
                break;
            if (max < average * 1.05 && min > average / 1.05)
                break;
            if (max >= average * 1.05)
                newDatas[imax] = -1;
            if (min <= average / 1.05)
                newDatas[imin] = -1;
        }
        SendDispAverageMessage("平均值 ：" + average);
        return average;
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    DisplayMessage((String) msg.obj);
                    break;
                case 2:
//                    DisplayData((int[]) msg.obj);
                    break;
                case 3:
                    DrawLineChart();
                    break;
                case 4:
                    DisplayMessage("AD: " + (int) msg.obj);
                    break;
                case 5:
                    DisplayAreaMessage((String) msg.obj);
                    break;
                case 6:
                    DisplayAverageMessage((String) msg.obj);
                    break;
                case 7:
                    DisplayCortisolResultMessage((String)msg.obj);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void DrawLineChart() {
        if (mListResult == null || mListResult.size() <= 0) {
            Toast.makeText(this, "没有数据", Toast.LENGTH_LONG).show();
            return;
        }

        List<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
//        for (int fx = 0; fx < 10; fx++) {
//            if (!bF8ClearNIR[fx]) continue;
        List<Entry> entries = new ArrayList<Entry>();
//            for (int i = 0; i < mListResult.get(fx).size(); i++) {
//                entries.add(new Entry(mStart + i * mStep, mListResult.get(fx).get(i)));
//            }
        for (int i = 0; i < mListResult.size(); i++)
            entries.add(new Entry(mStart + i * 1.0f / mStep, mListResult.get(i)));
//            LineDataSet dataSet = new LineDataSet(entries, mstrWaveLength[fx]);
//        int color = GetColor(fx);
        LineDataSet dataSet = new LineDataSet(entries, "ad");
        int color = GetColor(0);
        dataSet.setColor(color);
        dataSet.setValueTextColor(color);
        dataSet.setCircleColor(color);
        dataSet.setCircleHoleColor(color);
        dataSets.add(dataSet);
//        }
        LineData data = new LineData(dataSets);
        mLineChart.setData(data);
        mLineChart.invalidate(); // refresh
    }

    int[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.GRAY, Color.DKGRAY, Color.LTGRAY, Color.CYAN, Color.BLACK, Color.MAGENTA, Color.WHITE};

    private int GetColor(int i) {
        return colors[i % 10];
    }

    boolean scanReadAD(boolean bOpenLed, int start, int stop, int step, List<Integer> listResult, boolean bMove) {
        mDeviceHID.StopADReceive();
        mDeviceHID.Skip();
        if(bMove)
            mDeviceHID.GoHome();

        if (bOpenLed && !LEDOn()) {
            SendDispMessage("开灯失败");
            return false;
        }
        listResult.clear();
        mDeviceHID.Skip();

        if(bMove)
            if (!mDeviceHID.MoveTray(start)) {
                if (!mDeviceHID.MoveTray(start)) {
                    SendDispMessage("移动到起点位置 " + start + " 失败");
                    mDeviceHID.StopADReceive();
                    if (bOpenLed)
                        LEDOff();
                    mDeviceHID.MoveTray(0);
                    return false;
                }
            }
        mDeviceHID.StartADReceive(adPosition);
        if(bMove)mDeviceHID.StartMoveTray(stop);
        mDeviceHID.GetADAfterStart();
        mDeviceHID.GetADAfterStart();
        mDeviceHID.GetADAfterStart();
        int nData = 0;
        while (true) { //连续读
            int data = mDeviceHID.GetADAfterStart();
            if (data <= 0&&bMove) {
                break;
            }
            listResult.add(data);
            DispCurve();
            nData++;
            if (nData > (stop - start) * step + 100) {
                SendDispMessage("没有接收到停止命令，强制停止");
                break;
            }
        }
        mDeviceHID.StopADReceive();
        if (bOpenLed)
            mDeviceHID.LEDOn(ledPosition, (byte) 0x00, 0);
        if(bMove)mDeviceHID.MoveTray(0);
        return true;
    }
}